var stompClient = null;

var headers={token:"123456"};
var seesionId=null;
function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    if (connected) {
        $("#conversation").show();
    }
    else {
        $("#conversation").hide();
    }
    $("#greetings").html("");
}

function connect() {
    seesionId=$("#uname").val();
    var socket = new SockJS('/portfolio');
    stompClient = Stomp.over(socket);

    stompClient.connect(headers, function (frame) {
        setConnected(true);
        console.log('Connected***********: ' + frame);
        stompClient.subscribe('/topic/greetings', function (greeting) {
           console.log(greeting+"*********");
           var parse = JSON.parse(greeting.body);
            showGreeting("用户:"+parse.uname+"    发出的消息："+parse.message);
            //greeting.ack();
        });
       stompClient.subscribe('/user/'+seesionId+'/one', function (greeting) {
       var parse = JSON.parse(greeting.body);

            showGreeting("专属自己的频道消息："+parse.message);
        });
    });
}

function disconnect() {
    if (stompClient !== null) {
        stompClient.disconnect();
    }
    setConnected(false);
    console.log("Disconnected****");
}

function sendName() {
    stompClient.send("/app/hello", headers, JSON.stringify({'name': $("#name").val(),
        'uname':$("#uname").val(),
         'message':$("#content").val()}));
}
function send2() {
   var user = $("#content2").val();
   var content = $("#content3").val();
   console.log(user+"****"+content);
    $.ajax({
        type: 'POST',
        url: "http://localhost:9080/websocket/user/message",
        data:{
            username:user,
            message:content,
        },
        success: function(data){
            console.log(data);
            // var code = JSON.parse(data).code;
        },
        error: function(){
        }
    })


}

function showGreeting(message) {
    console.log(message+"************")
    $("#greetings").append("<tr><td>" + message + "</td></tr>");
}

$(function () {
    $("form").on('submit', function (e) {
        e.preventDefault();
    });
    $( "#connect" ).click(function() {
        connect(); });
    $( "#disconnect" ).click(function() {
        disconnect(); });
    $( "#send" ).click(function() {
        sendName(); });
    $( "#send2" ).click(function() {
        send2(); });

});

